package net.hxz.modules.controller.backEnd;

import javax.servlet.http.HttpServletResponse;

import net.hxz.modules.controller.BaseController;
import net.hxz.modules.pojo.Type;
import net.hxz.modules.services.ITypeService;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("backEnd/type/")
public class BackEndTypeController extends BaseController{
	private final String PATH = "backEnd/modules/type/";
	
	@Autowired
	private ITypeService typeService;
	
    @RequestMapping("loadTree")
    public void loadTree(Long typeId, HttpServletResponse response) throws Exception {
        if(null == typeId)
        	typeId = 0L;
        
        JSONArray arrays = new JSONArray();
        for (Type type : typeService.getByParent(typeId)) {
        	 JSONObject tempObject = new JSONObject();
             tempObject.put("name", type.getName());
             tempObject.put("id", type.getTypeId());
             tempObject.put("isParent", typeService.countByParent(type.getTypeId()) > 0);
             arrays.put(tempObject);
        }
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(arrays.toString());
    }
    
    @RequestMapping("list")
    public String list(Long typeId, ModelMap map) {
        return PATH + "list";
    }
    
    @RequestMapping("newRoot")
    public String newRoot() {
        return PATH + "newRoot";
    }
    
    @RequestMapping("type")
    public String type(Long typeId, ModelMap map) {
    	map.put("type", typeService.get(typeId));
        return PATH + "type";
    }
    
	@RequestMapping(value = "/add.json")
	public void add(Type type, ModelMap map) {
		typeService.add(type);
	}
	
	@RequestMapping(value = "/mod.json")
	public void mod(Type type, ModelMap map) {
		typeService.modify(type);
	}
	
	@RequestMapping(value = "/del.json")
	public void del(Long typeId, ModelMap map) {
		if(typeService.countByParent(typeId) > 0){
			super.createJSONError(map, "还有东西没删干净！");
			return;
		}
		typeService.del(typeId);
	}
}

